package cn.pn.project.service;

import cn.pn.project.common.DtoUtil;
import cn.pn.project.mapper.commodity.ShowtypeDao;
import cn.pn.project.pojo.commodity.Commodity;
import cn.pn.project.pojo.commodity.Showtype;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class ItemService {
    @Autowired
    private ShowtypeDao showtypeDao;
    @Resource
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "/listAllType", method = RequestMethod.GET)
    public List<Showtype> listAllType() {
        String key = "allKey_";
        ValueOperations<String, List<Showtype>> operations = redisTemplate.opsForValue();
        boolean hasKey = redisTemplate.hasKey(key);
        System.out.println("是否含有此键值"+hasKey+"---------------***********");

        if (hasKey) {
            List<Showtype> allFatherType = operations.get(key);
            System.out.println("==========从缓存中获得数据=========   父级类型总数==》 "+allFatherType.size());
            return allFatherType;
        } else {
            List<Showtype> allFatherType = showtypeDao.listAllType();
            System.out.println("==========从数据表中获得数据=========  父级类型总数==》"+allFatherType.size());


            // 写入缓存，时长5分钟，过后清除缓存
            operations.set(key, allFatherType, 5, TimeUnit.MINUTES);
            return allFatherType;
        }


        //return showtypeDao.listAllType();
    }

    @RequestMapping(value = "/listChildTypeByFatherId", method = RequestMethod.POST)
    public List<Showtype> listChildTypeByFatherId(@RequestParam("fatherId") Integer fatherId){
        return showtypeDao.listChildTypeByFatherId(fatherId);
    }

    /**
     * 根据类别id获取类别名称
     * @param typeId
     * @return
     */
    @RequestMapping(value = "/getTypeNameByTypeId", method = RequestMethod.POST)
    String getTypeNameByTypeId(@RequestParam("typeId")Integer typeId){
        return showtypeDao.getTypeNameByTypeId(typeId);
    }




}
